
#!/bin/bash


#SHELL_PATH=`dirname $0`
#echo "执行路径：$SHELL_PATH"
#cd $SHELL_PATH


KDHAppFileName="NeiTui"
#需要拷贝的资源
KDHBundleName="ZHPlugin.bundle"
#需要拷贝动态库名称，ZHPlugin.framework
KDHDylibName="ZHPlugin"
#签名
KDHCodeSign="Apple Development: Jing Li (5U2C376AVD)"
#修改后的包名
KDHBundleId="com.zhihan.faq"


#copy 可执行文件
echo "### clean app"
rm -rf ./Payload
rm -rf ./Payload.ipa
mkdir -p ./Payload

#copy app
echo "### copy app"
cp -r ./file/${KDHAppFileName}-backup.app "./Payload/${KDHAppFileName}.app"
cp -r "./file/${KDHAppFileName}-backup.decrypt" "./Payload/${KDHAppFileName}.app/${KDHAppFileName}"
chmod +x "./Payload/${KDHAppFileName}.app/${KDHAppFileName}"

rm -rf ./Payload/${KDHAppFileName}.app/Plugins/**
rm -rf ./Payload/${KDHAppFileName}.app/Plugins
rm -rf ./Payload/${KDHAppFileName}.app/Watch/**
rm -rf ./Payload/${KDHAppFileName}.app/Watch

#copy frameworks
if [ -d "./file/copy-frameworks" ]; then
    for framework in "./file/copy-frameworks/"*
    do
        echo "### copy ${framework}"
        cp -rf "${framework}" "./Payload/${KDHAppFileName}.app/Frameworks/"
    done
fi

#copy framework
if [ -d "./file/${KDHDylibName}.framework" ]; then
    cp -rf "./file/${KDHDylibName}.framework" "./Payload/${KDHAppFileName}.app/Frameworks/"
    ./tools/yololib ./Payload/${KDHAppFileName}.app/${KDHAppFileName} Frameworks/${KDHDylibName}.framework/${KDHDylibName}
#    /usr/bin/codesign --force --sign "$KDHCodeSign" "./Payload/${KDHAppFileName}.app/Frameworks/${KDHDylibName}.framework"
fi

#copy provision
cp -rf ./file/embedded.mobileprovision ./Payload/${KDHAppFileName}.app/embedded.mobileprovision

#copy bundle
echo "### copy bundle"
if [ -d "./file/$KDHBundleName" ]; then
    rm -rf "./Payload/${KDHAppFileName}.app/${KDHBundleName}"
    cp -rf "./file/${KDHBundleName}" "./Payload/${KDHAppFileName}.app/"
    if [ ! $? -eq 0 ]; then
        echo "copy bundle error"
        exit 1
    fi
fi

#更新 Info.plist bundleID
echo "### update bundleId"
/usr/libexec/PlistBuddy -c "Set :CFBundleIdentifier $KDHBundleId" "./Payload/${KDHAppFileName}.app/Info.plist"


#重新签名 app/Frameworks
echo "### start sign"
if [ -d "./Payload/${KDHAppFileName}.app/Frameworks" ]; then
    for framework in "./Payload/${KDHAppFileName}.app/Frameworks/"*
    do
        /usr/bin/codesign --force --sign "$KDHCodeSign" "$framework"
    done
fi


# Entitlements.plist
if [ -f "./file/Entitlements.plist" ]; then
    cp -rf "./file/Entitlements.plist" ./Payload/
    codesign -fs "$KDHCodeSign"  --no-strict --entitlements=./Payload/Entitlements.plist ./Payload/${KDHAppFileName}.app
    if [ ! $? -eq 0 ]; then
        echo "codesign app error"
        exit 1
    fi
fi

# 开始打包
echo "### start package"
zip -r "./${KDHAppFileName}.ipa" ./Payload >/dev/null 2>&1
#xcrun -sdk iphoneos -v ./Payload/${KDHAppFileName}.app -o ./${KDHAppFileName}.ipa
if [ ! $? -eq 0 ]; then
    echo "打包失败"
    exit 1
fi
rm -rf ./Payload
echo "打包成功"
